/*
 * @Author: 肖思汗 
 * @Date: 2025-07-12 10:58:26 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-09-03 15:23:01
 */

import { ArrowRight, Heart, HeartFill } from '@nutui/icons-react-taro';
import { Badge, Button, Col, Row, Swiper, Tour } from '@nutui/nutui-react-taro';
import { Image, RichText, Text, View } from '@tarojs/components';
import Taro, { useDidHide, useDidShow, useLoad } from '@tarojs/taro';
import clsx from 'clsx';
import { autorun, toJS } from 'mobx';
import { observer } from "mobx-react-lite";
import { ReactNode, useEffect, useRef, useState } from 'react';
import ColorItem from 'src/components/ColorItem/ColorItem';
import CustomHeader from 'src/components/CustomHeader/CustomHeader';
import MyVideo from 'src/components/MyVideo/MyVideo';
import PageLayer from 'src/components/PageLayer/PageLayer';
import UtTag from 'src/components/UtTag/UtTag';
import shoppingCartStore from 'src/pages/ShoppingCart/shoppingCartStore';
import userStore from 'src/pages/User/userStore';
import utils from 'src/utils/utils';
import utilsStore from 'src/utils/utilsStore';
import { GoodsBaseData, GoodsData } from 'types/type';
import toDesign from '../Design/designComponent/toDesign';
import myCollectionApi from '../MyCollection/myCollectionApi';
import styles from './goodsDetail.module.less';
import goodsDetailStore from './goodsDetailStore';
import './quill.snow.less';
import customer_servicePNG from './customer_service.png';
import carPNG from './car.png';
import join_carPNG from './join_car.png';
import { filter } from 'lodash';

interface Iprops {
    children?: ReactNode
}

// 商品详情页
const GoodsDetail = observer((props: Iprops) => {

    const swiperRef = useRef(null);
    const [showTour, setShowTour] = useState(false);

    useLoad(() => {
        //开启分享
        Taro.showShareMenu({
            withShareTicket: true,
        });
    });

    useDidShow(() => {
        // if (swiperRef.current) {
        //     //@ts-ignore
        //     swiperRef.current.to(0);
        // }
        setTimeout(() => {
            if (utilsStore.showTour3) {
                utilsStore.setShowTour3(false);
                setShowTour(true);
            }
        }, 1500);
    });

    useDidHide(() => {
        setShowTour(false);
    });

    const { productId } = Taro.getCurrentInstance().router?.params || {};

    const sizeImgRef = useRef<HTMLDivElement>(null);

    const [goodsData, setGoodsData] = useState<GoodsData>(toJS(goodsDetailStore.goodsData));

    const [goodsBaseData, setGoodsBaseData] = useState<GoodsBaseData>(toJS(goodsDetailStore.goodsBaseData));

    const [isFavorite, setIsFavorite] = useState(goodsDetailStore.goodsData.ifCollect);

    const [swiperIndex, setSwiperIndex] = useState<number>(0);

    useEffect(() => autorun(() => {
        setGoodsData(toJS(goodsDetailStore.goodsData));
        setGoodsBaseData(toJS(goodsDetailStore.goodsBaseData));
        setIsFavorite(goodsDetailStore.goodsData.ifCollect);
    }, { delay: 30 }), []);

    const [shoppingCartNumber, setShoppingCartNumber] = useState(0);

    useEffect(() => autorun(() => {
        setShoppingCartNumber(shoppingCartStore.list.length);
    }, { delay: 30 }), []);

    useEffect(() => {
        userStore.awaitLogined().then(() => {
            console.log("productId", productId);
            if (productId) {
                goodsDetailStore.getGoodsDatails(productId);
            }
        });
        return () => { };
    }, []);

    // 滚动页面到尺码图片的位置
    const scrollToSizeImg = () => {
        const query = Taro.createSelectorQuery();
        query
            .select('.' + styles.sizeImg)
            .boundingClientRect()
            .selectViewport()
            .scrollOffset()
            .exec((res) => {
                if (res[0] && res[1]) {
                    const offsetTop = res[0].top + res[1].scrollTop - 94;
                    Taro.pageScrollTo({
                        scrollTop: offsetTop,
                        duration: 300,
                    });
                }
            });
    };

    // 颜色对应的衣服
    const cloths: Array<string> = [];
    if (goodsData.productData.colorThumbs) {
        goodsData.productData.colorThumbs.map((color) => {
            if (goodsDetailStore.selectedColor === color.cn) {
                if (color.fontThumbImg) {
                    cloths.push(color.fontThumbImg);
                }
                if (color.backThumbImg) {
                    cloths.push(color.backThumbImg);
                }
            }
        });
    }

    return (
        <PageLayer
            hasTabBar={false}
            hasHeader={true}
            showBack={true}
            style={{
                paddingBottom: utilsStore.barBottom,
            }}
        >

            <View className={styles.goodsDetail}>

                {/* 收藏按钮 */}
                <View
                    className={styles.favoriteButton}
                    onClick={() => {
                        if (isFavorite) {
                            setIsFavorite(false);
                            myCollectionApi.editMyCollect(goodsData.productId); // 取消收藏
                        } else {
                            setIsFavorite(true);
                            myCollectionApi.addMyCollect(goodsData.productId); // 收藏
                        }
                    }}
                >
                    <View className={styles.favoriteBackground} />
                    {
                        isFavorite ?
                            <HeartFill
                                className={styles.favoriteIcon}
                                color={"#fd7901"}
                            /> :
                            <Heart
                                className={styles.favoriteIcon}
                                color={"#ffffff"}
                            />
                    }
                </View>

                {/* 
                    <View
                        ref={contentRef}
                        className={styles.content}
                        style={{ height: sysInfo.windowHeight - navBarHeight - statusBarHeight }}
                    >
                */}

                <Swiper
                    defaultValue={0}
                    loop
                    autoPlay={false}
                    indicator
                    ref={swiperRef}
                    className={styles.swiper}
                    height={utilsStore.windowWidth}
                    onChange={(e) => {
                        // console.log("swiper:", e.detail.current);
                    }}
                    onAnimationFinish={(e) => {
                        setSwiperIndex(e.detail.current);
                    }}
                >
                    {filter([...goodsData.productData.thumbs, ...cloths]).map((thumb: string, index) => (
                        <Swiper.Item key={index}>
                            {
                                /(jpg|png|peg|webp)$/i.test(thumb) &&
                                <Image
                                    style={{ width: '100vw', height: '100vw' }}
                                    onClick={() => {
                                        Taro.previewImage({
                                            urls:
                                                filter([
                                                    ...goodsData.productData.thumbs,
                                                    ...cloths
                                                ])
                                                    .filter((url: string) => /(jpg|png|peg|webp)$/i.test(url))
                                                    .map(url => utils.ossSuffix(url)),
                                        });
                                    }}
                                    mode="aspectFit"
                                    src={utils.ossSuffix(thumb)}
                                />
                            }
                            {
                                /(mp4)$/i.test(thumb) &&
                                <MyVideo
                                    className={styles.video}
                                    src={utils.ossSuffix(thumb)}
                                    resetIndex={swiperIndex}
                                />
                            }
                        </Swiper.Item>
                    ))}
                </Swiper>

                <View className={styles.goodsName} >
                    <Text className={styles.symbol}>￥</Text>
                    <Text className={styles.price} >{goodsData.pagePrice}</Text>
                    <Text className={styles.originalPrice} >原价: ￥{goodsData.underlinePrice}</Text>
                    {
                        goodsData.ifPinkage === "是" &&
                        <UtTag
                            style={{
                                margin: "0px 0px 0px 10px",
                                verticalAlign: "middle",
                                position: "relative",
                                top: 0
                            }}
                        >包邮</UtTag>
                    }
                    <UtTag
                        style={{
                            margin: "0px 0px 0px 10px",
                            verticalAlign: "middle",
                            position: "relative",
                            top: 0
                        }}
                    >含图案定制</UtTag>
                    <View className={styles.goodsNameText} >{goodsData.productName}</View>
                    <View className={styles.describe}>
                        {goodsData.protection}
                        {/* 每件,含正面印花,不含运费
                    <Text className={styles.describeLable} >(说明)</Text> */}
                    </View>
                </View>

                {/* 尺码和颜色 */}
                <Row className={styles.sizeColor} >
                    <Row className={styles.sizeRow} >
                        <Col span={3} >
                            <Text className={styles.lable} >尺码:</Text>
                        </Col>
                        <Col
                            span={14}
                            className={styles.sizeBox}
                        >
                            {goodsBaseData.data.sizes.filter(s => s.enable).map((s) => (
                                <Text
                                    key={s.name}
                                    className={clsx(styles.sizeButton, goodsDetailStore.selectedSize === s.name && styles.active)}
                                    onClick={() => goodsDetailStore.selectSize(s.name)}
                                >
                                    {s.name}
                                </Text>
                            ))}
                        </Col>
                        <Col span={1} >
                            <View className={styles.sizeMask} ></View>
                        </Col>
                        <Col span={6} >
                            <Text
                                className={styles.sizeRecommen}
                                onClick={scrollToSizeImg}
                            >
                                尺码推荐
                                <ArrowRight className={styles.icon} />
                            </Text>
                        </Col>
                    </Row>
                    {
                        goodsBaseData.data.colors.length > 0 &&
                        <Row className={styles.colorRow} >
                            <Col span={3} >
                                <Text className={styles.colorLable} >颜色:</Text>
                            </Col>
                            <Col span={21} >
                                {goodsBaseData.data.colors.map((c, index) => (
                                    <ColorItem
                                        key={index}
                                        color={c.color}
                                        active={goodsDetailStore.selectedColorValue === c.color}
                                        onClick={() => {
                                            goodsDetailStore.selectColor(c.cn || "", c.color);
                                        }}
                                    />
                                ))}
                            </Col>
                        </Row>
                    }
                </Row>

                {/* 尺码说明的图片 */}
                <Image
                    mode="widthFix"
                    ref={sizeImgRef}
                    className={styles.sizeImg}
                    src={utils.ossSuffix(goodsData.sizeRecommendImageUrl, 1024)}
                    onClick={() => {
                        Taro.previewImage({
                            urls: [utils.ossSuffix(goodsData.sizeRecommendImageUrl, 1024)],
                            current: utils.ossSuffix(goodsData.sizeRecommendImageUrl)
                        })
                    }}
                />

                {/* 商品详情富文本 */}
                <View className={styles.richText}>
                    <RichText
                        className="ql-editor"
                        nodes={goodsData.productRemark.replace(/<img([^>]*)>/g, '<img style="max-width:100%;height:auto;" $1>')}
                        onClick={(e) => {
                            const imgUrls = (goodsData.productRemark.match(/<img[^>]+src="([^">]+)"/g) || [])
                                ?.map(item => item.match(/src="([^">]+)"/)[1]) || [];
                            Taro.previewImage({
                                urls: imgUrls.map(url => utils.ossSuffix(url, 1024)),
                            });
                        }}
                    />
                </View>

                {/* 底部按钮 */}
                <View
                    className={styles.bottomBtn}
                    style={{
                        paddingBottom: utilsStore.safeAreaBottom || utils.rpx2px(20)
                    }}
                >
                    <View className={styles.btns} >
                        <Button
                            fill="none"
                            openType='contact'
                            style={{
                                padding: '0rpx',
                            }}
                        >
                            <Image src={customer_servicePNG} className={styles.icon} />
                        </Button>

                        <Badge value={shoppingCartNumber}>
                            <Image
                                src={carPNG}
                                className={styles.icon}
                                onClick={async () => {
                                    Taro.setStorageSync("productId", productId);
                                    Taro.switchTab({
                                        url: '/pages/ShoppingCart/ShoppingCart',
                                        success: () => {
                                        }
                                    });
                                }}
                            />
                        </Badge>

                        <Image
                            src={join_carPNG}
                            className={styles.icon}
                            onClick={async () => {
                                goodsDetailStore.joinCart();
                            }}
                        />

                        {/* 
                            <Button
                                id="joinCart"
                                type="warning"
                                loading={goodsDetailStore.joining}
                                className={styles.toDesign}
                                onClick={async () => {
                                    goodsDetailStore.joinCart();
                                }}
                            >
                                加入购物车
                            </Button> 
                        */}

                        <Button
                            id="toDesign"
                            type="warning"
                            loading={goodsDetailStore.joining}
                            className={styles.toDesign}
                            onClick={async () => {
                                const { goodsData, goodsBaseData } = goodsDetailStore;
                                await toDesign({
                                    productId: goodsData.productId,
                                    productNegativeId: goodsBaseData.productNegativeId,
                                    designName: goodsData.productName,
                                    size: goodsDetailStore.selectedSize,
                                    color: goodsDetailStore.selectedColor,
                                    colorValue: goodsDetailStore.selectedColorValue,
                                    needupload: true,
                                })
                            }}
                        >
                            {/* 二次创作 */}
                            去创作
                        </Button>
                    </View>
                </View>

            </View >
            <Tour
                className="nut-custom-tour"
                visible={showTour}
                onClose={() => {
                    utilsStore.setShowTour3(false);
                    setShowTour(false);
                }}
                list={[
                    {
                        content: '3.点击此处开始设计',
                        location: "top-end",
                        target: 'toDesign',
                    },
                    // {
                    //     content: '4.点击此处加入购物车',
                    //     location: "top-start",
                    //     target: 'joinCart',
                    // }
                ]}
                offset={[0, 0]}
                maskWidth={utils.rpx2px(320)}
                maskHeight={utils.rpx2px(100)}
            />
        </PageLayer>
    );
});

export default GoodsDetail;